import 'package:apivideo_live_stream/apivideo_live_stream.dart';
import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/data/entities/application/ticket_plan_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/live/params.dart';
import 'package:flutter/services.dart';
import 'package:wakelock_plus/wakelock_plus.dart';

/// 直播页面
class LiveViewPage extends StatefulWidget {
  const LiveViewPage({super.key});

  @override
  State<LiveViewPage> createState() => _LiveViewPageState();
}

class _LiveViewPageState extends State<LiveViewPage> with WidgetsBindingObserver {
  final ButtonStyle buttonStyle = ElevatedButton.styleFrom(textStyle: const TextStyle(fontSize: 20));
  // 直播参数
  LiveParams config = LiveParams();
  late final ApiVideoLiveStreamController _controller;
  bool _isStreaming = false;

  TicketPlanReceiptLists ticketPlanReceiptLists = Get.arguments as TicketPlanReceiptLists;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);

    _controller = createLiveStreamController();

    _controller.initialize().catchError((e) {
      AppToast.showError(e.toString());
    });
    super.initState();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.inactive) {
      _controller.stop();
      // closeLive();
    } else if (state == AppLifecycleState.resumed) {
      _controller.startPreview();
    }
  }

  ApiVideoLiveStreamController createLiveStreamController() {
    return ApiVideoLiveStreamController(
      initialAudioConfig: config.audio,
      initialVideoConfig: config.video,
      onConnectionSuccess: () {
        AppLogger.devLog('连接成功');
      },
      onConnectionFailed: (error) {
        AppLogger.devLog('连接失败: $error');
        _showDialog(context, '连接失败', error);
        if (mounted) {
          setIsStreaming(false);
        }
      },
      onDisconnection: () {
        AppToast.showError('断开连接');
        if (mounted) {
          setIsStreaming(false);
        }
      },
    );
  }


  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (!_isStreaming) {
          return true;
        }
        await showDialog<bool>(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('提示'),
              content: const Text('是否离开直播页面'),
              actions: <Widget>[
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    onStopStreamingButtonPressed();
                    Navigator.of(context).pop(true);
                    Get.back();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
        return false;
      },
      child: Scaffold(
        appBar: CustomAppBar(
          titleText: '过程影像',
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(1.0),
                  child: Center(
                    child: ApiVideoCameraPreview(controller: _controller),
                  ),
                ),
              ),
              _controlRowWidget()
            ],
          ),
        ),
      ),
    );
  }

  /// 显示带有按钮的控制栏，用于拍照和录制视频。
  Widget _controlRowWidget() {
    final ApiVideoLiveStreamController liveStreamController = _controller;

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        TextButton(
          onPressed: liveStreamController != null ? onSwitchCameraButtonPressed : null,
          child: const Text('旋转镜头'),
        ),
        // IconButton(
        //   icon: const Icon(Icons.mic_off),
        //   color: Colors.blue,
        //   onPressed: liveStreamController != null
        //       ? onToggleMicrophoneButtonPressed
        //       : null,
        // ),
        TextButton(
          onPressed: !_isStreaming ? onStartStreamingButtonPressed : null,
          child: const Text('开始直播'),
        ),
        TextButton(
            onPressed: _isStreaming ? onStopStreamingButtonPressed : null,
            child: Text(
              '结束直播',
              style: TextStyle(
                color: _isStreaming ? Colors.red : Colors.grey,
              ),
            )),
      ],
    );
  }

  Future<void> switchCamera() async {
    final ApiVideoLiveStreamController liveStreamController = _controller;

    if (liveStreamController == null) {
      AppToast.showError('错误:先创建相机控制器。');
      return;
    }

    return await liveStreamController.switchCamera();
  }

  Future<void> toggleMicrophone() async {
    final ApiVideoLiveStreamController liveStreamController = _controller;

    if (liveStreamController == null) {
      AppToast.showError('错误:先创建相机控制器。');
      return;
    }

    return await liveStreamController.toggleMute();
  }

  Future<void> startStreaming() async {
    final ApiVideoLiveStreamController controller = _controller;

    if (controller == null) {
      AppLogger.devLog('错误:先创建相机控制器。');
      return;
    }

    return await controller.startStreaming(streamKey: ticketPlanReceiptLists.id!, url: Interface.rtmpUrl);
  }

  Future<void> stopStreaming() async {
    final ApiVideoLiveStreamController controller = _controller;

    if (controller == null) {
      AppLogger.devLog('错误:先创建相机控制器。');
      return;
    }

    return await controller.stopStreaming();
  }

  void onSwitchCameraButtonPressed() {
    switchCamera().then((_) {
      if (mounted) {
        setState(() {});
      }
    }).catchError((error) {
      if (error is PlatformException) {
        _showDialog(context, '错误', '切换摄像机失败: ${error.message}');
      } else {
        _showDialog(context, '错误', '切换摄像机失败: $error');
      }
    });
  }

  void onToggleMicrophoneButtonPressed() {
    toggleMicrophone().then((_) {
      if (mounted) {
        setState(() {});
      }
    }).catchError((error) {
      if (error is PlatformException) {
        _showDialog(context, '错误', '静音切换失败: ${error.message}');
      } else {
        _showDialog(context, '错误', '静音切换失败: $error');
      }
    });
  }

  void onStartStreamingButtonPressed() {
    startStreaming().then((_) {
      if (mounted) {
        setIsStreaming(true);
        startLiveThen();
      }
    }).catchError((error) {
      if (error is PlatformException) {
        _showDialog(context, 'Error', 'Failed to start stream: ${error.message}');
      } else {
        _showDialog(context, 'Error', 'Failed to start stream: $error');
      }
    });
  }

  void onStopStreamingButtonPressed() {
    stopStreaming().then((_) {
      if (mounted) {
        setIsStreaming(false);
        closeLive();
      }
    }).catchError((error) {
      if (error is PlatformException) {
        _showDialog(context, 'Error', 'Failed to stop stream: ${error.message}');
      } else {
        _showDialog(context, 'Error', 'Failed to stop stream: $error');
      }
    });
  }

  void setIsStreaming(bool isStreaming) {
    setState(() {
      _isStreaming = isStreaming;
    });
  }

  /// 直播开启后调用接口
  void startLiveThen() async {
    /// 保持屏幕常亮
    WakelockPlus.enable();

    final res = await HttpUtil().generatePostRequest(Interface.updateLiveStatus, data: {
      'id': ticketPlanReceiptLists.id,
    }).execute();

    res.onSuccess((result) {
      AppToast.showSuccess('直播开始');
    });
  }

  /// 关闭直播
  void closeLive() async {
    WakelockPlus.disable();
    final res = await HttpUtil().generatePostRequest(Interface.closeLiveStatus, data: {
      'id': ticketPlanReceiptLists.id,
      'type': 0,
    }).execute();

    res.onSuccess((result) {
      AppToast.showSuccess('直播结束');
    });
  }

}

Future<void> _showDialog(BuildContext context, String title, String description) async {
  return showDialog<void>(
    context: context,
    barrierDismissible: false, // user must tap button!
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text(title),
        content: SingleChildScrollView(
          child: Text(description),
        ),
        actions: <Widget>[
          TextButton(
            child: const Text('离开'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}
